package com.book.system.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.book.system.common.R;
import com.book.system.entity.User;
import com.book.system.service.UserService;
import com.book.system.service.impl.UserServiceImpl;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * 用户Servlet
 */
@WebServlet(name = "UserServlet", value = "/user")
@Slf4j
public class UserServlet extends BaseServlet {
    /**
     * 注入登陆Service
     */
    private final UserService userService = new UserServiceImpl();


    /**
     * 登陆操作
     *
     * @param request  请求对象
     * @param response 响应对象
     * @return R 返回结果
     */
    public R<String> login(HttpServletRequest request, HttpServletResponse response) {
        // 获取请求体
        String requestBody = getRequestBody(request);
        // 解析请求体
        User user = JSON.parseObject(requestBody, User.class);
        // 调用service层登陆方法
        if (userService.login(user, request.getSession())) {
            return R.success("登陆成功");
        }
        return R.error("登陆失败，请检查用户名、密码和你的身份是否正确");
    }

    /**
     * 获取当前登陆的用户菜单
     *
     * @param request  请求对象
     * @param response 响应对象
     * @return com.book.system.common.R<java.lang.String>
     * @author :刘林晓
     * @create time : 2024/4/27 22:27
     */
    public R<String> getMenu(HttpServletRequest request, HttpServletResponse response) {

        //获取session对象
        HttpSession session = request.getSession();
        //获取存放在session中的user对象
        User user = (User) session.getAttribute("user");
        if (user != null) {
            String menu = userService.getMenu(user.getFlag());
            if (menu != null && !"".equals(menu)) {
                return R.success(menu);
            }
        }
        return R.error(-1, "获取菜单失败,请尝试重新登陆");
    }

    /**
     * 退出登陆
     *
     * @param request  请求对象
     * @param response 响应对象
     * @return com.book.system.common.R<java.lang.String>
     * @author :刘林晓
     * @create time : 2024/4/27 22:26
     */
    public R<String> logout(HttpServletRequest request, HttpServletResponse response) {

        // 获取session对象
        HttpSession session = request.getSession();
        // 销毁session对象
        session.invalidate();
        return R.success("退出成功");
    }

    /**
     * 获取用户列表
     *
     * @param request  请求对象
     * @param response 响应对象
     * @return com.book.system.common.R<java.util.List < java.util.Map < java.lang.String, java.lang.Object>>>
     * @author :刘林晓
     * @create time: 2024/5/14 22:15
     */
    public R<List<Map<String, Object>>> getList(HttpServletRequest request, HttpServletResponse response) {

        // 获取前端传递的参数
        String name = request.getParameter("name");
        String flag = request.getParameter("flag");
        // 调用业务逻辑层方法
        List<Map<String, Object>> list = userService.getList(name, Integer.valueOf(flag));
        return R.success(list);

    }

    /**
     * 添加用户
     *
     * @param request  请求对象
     * @param response 响应对象
     * @return com.book.system.common.R<java.lang.String>
     * @author :刘林晓
     * @create time: 2024/5/14 22:19
     */
    public R<String> add(HttpServletRequest request, HttpServletResponse response) {

        //获取请求体数据
        String requestBody = getRequestBody(request);
        //将JSON字符串转换成Java对象
        User user = JSON.parseObject(requestBody, User.class);
        if (userService.add(user) == 1) {
            return R.success("添加成功");
        }
        return R.error("添加失败");
    }

    /**
     * 更新图书
     *
     * @param request  请求对象
     * @param response 响应对象
     * @return com.book.system.common.R<java.lang.String>
     * @author :刘林晓
     * @create time : 2024/5/9 12:32
     */
    public R<String> update(HttpServletRequest request, HttpServletResponse response) {
        //获取请求体数据
        String requestBody = getRequestBody(request);
        //将JSON字符串转换成Java对象
        User user = JSON.parseObject(requestBody, User.class);
        if (userService.updateById(user) == 1) {
            return R.success("修改成功");
        }
        return R.error("修改失败");
        // return userService.updateById(user) == 1 ? R.success("修改成功") : R.error("修改失败");

    }

    /**
     * 删除图书
     *
     * @param request  请求对象
     * @param response 响应对象
     * @return com.book.system.common.R<java.lang.String>
     * @author :刘林晓
     * @create time : 2024/5/9 12:32
     */
    public R<String> delete(HttpServletRequest request, HttpServletResponse response) {
        //获取前端参数
        String id = request.getParameter("id");
        if (userService.delete(Integer.valueOf(id)) == 1) {

            return R.success("删除成功");
        }
        return R.error("删除失败");
    }

    /**
     * 修改当前用户的密码
     *
     * @param request  请求对象
     * @param response 响应对象
     * @return com.book.system.common.R<java.lang.String>
     * @author :刘林晓
     * @create time: 2024/5/28 22:07
     */
    public R<String> rePassword(HttpServletRequest request, HttpServletResponse response) {

        String requestBody = getRequestBody(request);
        JSONObject jsonObject = JSON.parseObject(requestBody);
        String oldPassword = (String) jsonObject.get("oldPassword");
        String newPassword = (String) jsonObject.get("newPassword");
        if (oldPassword == null || newPassword == null) {
            return R.error("参数错误");
        }
        log.info("修改密码，旧密码：{}，新密码：{}", oldPassword, newPassword);
        // 获取session对象
        User user = (User) request.getSession().getAttribute("user");
        //判断旧密码是否正确
        if (user.getPassword().equals(oldPassword)) {
            user.setPassword(newPassword);
            if (userService.rePassword(user) == 1) {
                return R.success("修改成功");
            } else {

                return R.error("修改失败");
            }
        } else {
            return R.error("修改失败，旧密码错误");
        }
    }

    /**
     * 获取当前登陆者的信息
     *
     * @param request  请求对象
     * @param response 响应对象
     * @return com.book.system.common.R<com.book.system.entity.User>
     * @author :刘林晓
     * @create time: 2024/5/28 23:20
     */

    public R<User> getUsrInfo(HttpServletRequest request, HttpServletResponse response) {

        // 获取session对象
        HttpSession session = request.getSession();
        // 获取存放在session中的user对象
        User user = (User) session.getAttribute("user");
        if (user != null) {
            user.setPassword("");
            return R.success(user);
        }
        return R.error(-1, "获取用户信息失败,请尝试重新登陆");
    }

    /**
     * 修改当前用户的信息
     * @author :刘林晓
     * @create time: 2024/5/29 22:15
     * @param request  请求对象
     * @param response 响应对象
     * @return com.book.system.common.R<java.lang.String>
     */
    public R<String> updateUserInfo(HttpServletRequest request, HttpServletResponse response) {

        String requestBody = getRequestBody(request);
        User user = JSON.parseObject(requestBody, User.class);
        if (userService.updateById(user) == 1) {
//            request.getSession().setAttribute("user", user);
            //获取session对象
            HttpSession session = request.getSession();
            //获取session中的user对象
            User userSession = (User) session.getAttribute("user");
            //获取session中的user对象的密码
            user.setPassword(userSession.getPassword());
            //更新session
            session.setAttribute("user", user);
            return R.success("修改成功",null);
        }
        return R.error("修改失败");
    }

}
